package com.song.shirospringboot.config;

import com.song.shirospringboot.pojo.User;
import com.song.shirospringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;

// 自定义用户领域  继承授权领域，重写授权，认证
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("UserRealm执行了=>授权 doGetAuthorizationInfo");
        // 1.自定义给登录的用户授权 user:add 权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");

        // 2.连接真实数据库，查出当前用户授权权限，用户表多了个perms字段，存放用户权限
        // 拿到但取个钱登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        // 设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("UserRealm执行了=>认证 doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;

        // 验证用户名+密码，实际数据从数据库中查
        //String name = "root";
        //String password = "123456";

        // 验证用户名： 如果不存在，抛出异常:UnknownAccountException
        //if (!userToken.getUsername().equals(name)){
        //    return null;
        //}
        // 验证用户名密码： 如果不存在，抛出异常:IncorrectCredentialsException
        // 验证码密码 shiro 做，不会让我们来做，避免密码泄露
        //return  new SimpleAuthenticationInfo("", password, "");


        // 连接真实数据库验证用户名、密码
        User user = userService.queryUserByName(userToken.getUsername());
        if (user == null){
            return null; //没有这个人，抛出异常:UnknownAccountException
        }

        // 如果登录成功了，将用户信息放入session，前端需要通过session是否有值，来控制登录按钮是否展示
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        System.out.println("doGetAuthenticationInfo session=>"+session.getId());
        System.out.println("doGetAuthenticationInfo登录用户名=>:" + userToken.getUsername()+"登录密码:"+ Arrays.toString(userToken.getPassword()));
        System.out.println("doGetAuthenticationInfo数据库用户名:" + user.getName()+"数据库密码:"+user.getPwd());

        return new SimpleAuthenticationInfo(user, user.getPwd(), "");

    }


}




